import pickle
import logging

# 设置日志记录器
logger = logging.getLogger('shopping_system')
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler = logging.FileHandler('shopping_system.log', encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

# 购物系统类
# 实例属性 -- 商品信息  系统说明信息  当前用户（多个用户）
# 方法 -- 登录注册  查看商品  添加购物车  结算

# 用户类
# 实例属性 -- 名字  密码  钱  购物车
# 方法 --

# user class
class User:
    def __init__(self, name, passwd, init_amount):
        self.name = name
        self.passwd = passwd
        self.init_amount = init_amount
        self.shopping_car = []

    def __repr__(self):
        return f'账户:{self.name}, 初始金额:{self.init_amount})'

# shopping_system
class ShoppingSystem:
    result1 = 0
    def __init__(self, goods_info, sys_info):
        self.goods_info = goods_info
        self.sys_info = sys_info
        self.userdict = {}

    def load_user(self):
        file_name = self.sys_info + "_user.pickle"
        try:
            with open(file_name, "rb") as fp:
                self.userdict = pickle.load(fp)
        except:
            pass


    def register(self, name, passwd, initial_amount):
        if name not in self.userdict:
            # 创建一个新用户， 实例化User类
            user = User(name, passwd, initial_amount)
            # 把名字作为key.user对象作为value 存在self.userdict里面
            self.userdict[name] = user
            file_name = self.sys_info + "_user.pickle"
            # 写入文件方法一:
            with open(file_name, "wb") as fp:
                pickle.dump(self.userdict, fp)
            # 写入文件方法二:
            # tmp_dict = {}
            # for k, v in self.userdict.items():
            #     tmp_dict[k] = {"passwd":v.passwd, "init_amount": v.init_amount}
            # with open(file_name, "w") as fp:
            #     fp.write( json.dumps(tmp_dict) )
            # 记录日志
            logger.info(f'新用户注册: {user}')
        else:
            print("用户已存在")





    def login(self, name, passwd):
        if name in self.userdict and passwd == self.userdict[name].passwd:
            print("登录成功")
            # 记录日志
            logger.info(f'登录的用户: {name}')
            return True
        else:
            print("账号或密码错误")
            return False

    def check(self):
        print("商品编号".ljust(10," "), "商品名字".ljust(10," "), "商品价格".ljust(10," "))
        for key in self.goods_info:
            product_name = self.goods_info[key]["name"]
            product_price = self.goods_info[key]["price"]
            print(f"{key}".ljust(10, " "), f"{product_name}".ljust(10, " "), f"{product_price}")
        # print(f"该购物系统支持购买的商品有:{self.goods_info}")



    def add_shopping_car(self, name, good, weight):
        if good in self.goods_info and int(self.goods_info[good]["price"] * int(weight)) <= int(self.userdict[name].init_amount):
            result1 = int(self.userdict[name].init_amount) - int(self.goods_info[good]["price"] * int(weight))  # 计算购买商品后的余额
            self.userdict[name].init_amount = result1  # 更新初始金额
            self.userdict[name].shopping_car.append({good: weight})  # 添加到购物车
            print("商品已成功购买。")
            print(self.userdict[name].init_amount)
            # 记录日志
            logger.info(f' {name}的购物车中加入了数量为{weight}的{good}')
        else:
            print("余额不足或商品不存在。")




    # def result(self, result1):
    #     if self.goods_info[good]["price"] <= self.userdict[name].init_amount:



fruit_goods = {
    'F0001': {"name": "苹果", "price": 8},
    'F0002': {"name": "香蕉", "price": 4}
}

medicine_goods = {
    'M0001': {"name": "奥司他韦", "price": 60},
    'M0002': {"name": "抗病毒口服液", "price": 30}
}

system1 = ShoppingSystem(fruit_goods, "水果购物系统")
system2 = ShoppingSystem(medicine_goods, "药品购物系统")

system = [system1, system2]

while 1:
    print("当前平台, 已有购物系统如下：")
    for k, v in enumerate(system):
        print(f"{k}.{v.sys_info}")
    c1 = input("请输入你的选择(按q退出)：")
    if c1 == "q":
        break
    if c1.isdigit() and int(c1) < len(system):
        c1 = int(c1)
        current_system = system[c1]
        #加载用户
        current_system.load_user()
        print(f"欢迎进入{current_system.sys_info}".center(40, "*"))
        while 1:
            c2 = input("1.登录\n2.注册\n请输入你的选择(按q退出):")
            if c2 == "q":
                break
            if c2 == "1":
                name, passwd = input("请输入你的名字、密码（用空白分割）:").split()
                if current_system.login(name, passwd):
                    while 1:
                        c3 = input("1.查看商品\n2.添加购物车并结算\n请输入你的选择(按q退出):")
                        if c3 == "q":
                            break
                        if c3 == "1":
                            current_system.check()
                        if c3 == "2":
                            while 1:
                                good, weight = input("请输入需购买商品的编号、数量:").split()
                                current_system.add_shopping_car(name, good, weight)
                                c4 = input("是否继续购买(按q退出，按1继续):")
                                if c4 == "q":
                                    break
                                else:
                                    continue







            elif c2 == "2":
                name, passwd, amount = input("请输入你的名字、密码、初始金额（用空白分割）:").split()
                current_system.register(name, passwd, amount)
                print("当前用户有:", end='\t')
                for i, n in enumerate(current_system.userdict):
                    print(n, end='\t')
                    if i == len(current_system.userdict) - 1:
                        print()
            else:
                print("输入有误！")
    else:
        print("输入有误，请重新输入！")
